<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/12 0012
 * Time: 上午 11:56
 */
namespace app\api\controller;

use app\admin\model\Storesettlement;
use app\admin\model\Userbuyticket;
use app\common\Helper;
use app\common\lib\Map;
use app\common\lib\Wx;
use app\common\model\Storecustradedetail;
use app\common\model\Storetradedetail;
use app\common\model\Userfocus;
use app\common\model\Userstore;
use app\common\validate\createStoreValidate;
use app\common\validate\IDMustBePostiveInt;
use think\Db;
use think\Exception;
use think\Request;

class Store extends Base{

    public function createMyStore(Request $request){
        (new createStoreValidate())->goCheck();
        $param = $request->param();
        Db::startTrans();
        try{
            if(isset($param['store']['id']) && !empty($param['store']['id'])){
                $storeModel = \app\admin\model\Store::get($param['store']['id']);
            }else{
                $Store = \app\admin\model\Store::where('contactPhone',$param['store']['contactPhone'])->where('status','<>',2)->find();
                if($Store){
                    return show(config('status.ERROR_STATUS'),'此手机号已被注册','此手机号已被注册');
                }
                $Userstore = Userstore::where('userId',$param['userId'])->find();
                if($Userstore){
                    return show(config('status.ERROR_STATUS'),'您已经有一个店铺了','您已经有一个店铺了');
                }
                $storeModel = new \app\admin\model\Store();
                $id = Helper::getUUID22();
                $storeModel->id = $id;
            }

            $storeModel->name = $param['store']['name'];
            $storeModel->imgUrl = $param['store']['imgUrl'];
            $storeModel->businessLicense = $param['store']['businessLicense'];
            $storeModel->address = $param['store']['address'];
            $storeModel->addressNumb = $param['store']['addressNumb'];
            $storeModel->lat = $param['store']['lat'];
            $storeModel->lng = $param['store']['lng'];
            $storeModel->phone = $param['store']['phone'];
            $storeModel->businessHours = $param['store']['businessHours'];
            $storeModel->contact = $param['store']['contact'];
            $storeModel->contactPhone = $param['store']['contactPhone'];
            $storeModel->typeId = $param['typeId'];
            $address = $this->getaddress($param['store']['lat'],$param['store']['lng']);
            $storeModel->province = $address['province'];
            $storeModel->city = $address['city'];
            $storeModel->area = $address['district'];
            $storeModel->details = $address['street'];
            $this->getshowPhoto($storeModel,$param['store']);
            $storeModel->save();
            if(isset($id) && !empty($id)){
                $Userstore = new Userstore();
                $Userstore->userId = $param['userId'];
                $Userstore->storeId = $id;
                $Userstore->save();
            }

            Db::commit();
            return show(config('status.SUCCESS_STATUS'),'创建店铺成功','创建店铺成功');
        }catch (Exception $ex){
            Db::rollback();
            return show(config('status.ERROR_STATUS'),$ex->getMessage(),$ex->getMessage());
        }

    }

    private function getshowPhoto($storeModel,$param){
        if(isset($param['showPhoto1']) && !isset($param['showPhoto2'])){
            $storeModel->showPhoto1 = $param['showPhoto1'];
        }
        if(isset($param['showPhoto2']) && !isset($param['showPhoto3'])){
            $storeModel->showPhoto1 = $param['showPhoto1'];
            $storeModel->showPhoto2 = $param['showPhoto2'];
        }
        if(isset($param['showPhoto3']) && !isset($param['showPhoto4'])){
            $storeModel->showPhoto1 = $param['showPhoto1'];
            $storeModel->showPhoto2 = $param['showPhoto2'];
            $storeModel->showPhoto3 = $param['showPhoto3'];
        }
        if(isset($param['showPhoto4']) && !isset($param['showPhoto5'])){
            $storeModel->showPhoto1 = $param['showPhoto1'];
            $storeModel->showPhoto2 = $param['showPhoto2'];
            $storeModel->showPhoto3 = $param['showPhoto3'];
            $storeModel->showPhoto4 = $param['showPhoto4'];
        }
        if(isset($param['showPhoto5']) && !isset($param['showPhoto6'])){
            $storeModel->showPhoto1 = $param['showPhoto1'];
            $storeModel->showPhoto2 = $param['showPhoto2'];
            $storeModel->showPhoto3 = $param['showPhoto3'];
            $storeModel->showPhoto4 = $param['showPhoto4'];
            $storeModel->showPhoto5 = $param['showPhoto5'];
        }
        if(isset($param['showPhoto6']) && !isset($param['showPhoto7'])){
            $storeModel->showPhoto1 = $param['showPhoto1'];
            $storeModel->showPhoto2 = $param['showPhoto2'];
            $storeModel->showPhoto3 = $param['showPhoto3'];
            $storeModel->showPhoto4 = $param['showPhoto4'];
            $storeModel->showPhoto5 = $param['showPhoto5'];
            $storeModel->showPhoto6 = $param['showPhoto6'];
        }
        if(isset($param['showPhoto7']) && !isset($param['showPhoto8'])){
            $storeModel->showPhoto1 = $param['showPhoto1'];
            $storeModel->showPhoto2 = $param['showPhoto2'];
            $storeModel->showPhoto3 = $param['showPhoto3'];
            $storeModel->showPhoto4 = $param['showPhoto4'];
            $storeModel->showPhoto5 = $param['showPhoto5'];
            $storeModel->showPhoto6 = $param['showPhoto6'];
            $storeModel->showPhoto7 = $param['showPhoto7'];
        }
        if(isset($param['showPhoto8']) && !isset($param['showPhoto9'])){
            $storeModel->showPhoto1 = $param['showPhoto1'];
            $storeModel->showPhoto2 = $param['showPhoto2'];
            $storeModel->showPhoto3 = $param['showPhoto3'];
            $storeModel->showPhoto4 = $param['showPhoto4'];
            $storeModel->showPhoto5 = $param['showPhoto5'];
            $storeModel->showPhoto6 = $param['showPhoto6'];
            $storeModel->showPhoto7 = $param['showPhoto7'];
            $storeModel->showPhoto8 = $param['showPhoto8'];
        }
        if(isset($param['showPhoto9'])){
            $storeModel->showPhoto1 = $param['showPhoto1'];
            $storeModel->showPhoto2 = $param['showPhoto2'];
            $storeModel->showPhoto3 = $param['showPhoto3'];
            $storeModel->showPhoto4 = $param['showPhoto4'];
            $storeModel->showPhoto5 = $param['showPhoto5'];
            $storeModel->showPhoto6 = $param['showPhoto6'];
            $storeModel->showPhoto7 = $param['showPhoto7'];
            $storeModel->showPhoto8 = $param['showPhoto8'];
            $storeModel->showPhoto9 = $param['showPhoto9'];
        }
    }

    private function getaddress($lat,$lng){
        return Map::geocoder($lat.','.$lng);
    }

    //生成店铺二维码
    public function getStoreCode($id = ''){
        (new IDMustBePostiveInt())->goCheck();


        $Store = \app\admin\model\Store::get($id);
        if($Store){
            if($Store->qrCode){
                return show(config('status.SUCCESS_STATUS'),'获取二维码成功',$Store->qrCode);
            }
            $res = Wx::getStoreCode($id);
            $Store->qrCode = $res;
            $Store->save();
            return show(config('status.SUCCESS_STATUS'),'获取二维码成功',$res);
        }else{
            return show(config('status.ERROR_STATUS'),'该店铺不存在','该店铺不存在');
        }


    }

    /**
     * 获取当前店铺的券的订单
     * @return \think\response\Json
     */
    public function getStoreOrder(Request $request){
        (new IDMustBePostiveInt())->goCheck();
        $param = $request->param();
        $field = 'a.*, u.id, u.userName,u.imgUrl';
        $jion = [
            ['user u','u.id=a.userId']
        ];
        $where['storeId'] = $param['id'];
        $where['status'] = 1;
        if(!empty($param['keywords'])){
            $keywords = $param['keywords'];
            $where['u.userName'] = ['like','%'.$keywords.'%'];
        }
        $order = 'createDate DESC';
        $res = model('userbuyticket')->alias('a')->where($where)->join($jion)->order($order)->field($field)->select();
        if($res){
            $Ticket = new \app\admin\model\Ticket();
            foreach ($res as &$v){
                $ticket = $Ticket->getTicket($v['ticketId']);
                $v['ticketName'] = $ticket['name'];
                $v['tickeimg'] = $ticket['backgroundImg'];

            }
            return show(config('status.SUCCESS_STATUS'),'ok',$res);
        }else{
            return show(config('status.ERROR_STATUS'),'error',[]);
        }

    }

    public function getStoreTickets(Request $request){
        $param = $request->param();
        $Store = \app\admin\model\Store::get($param['storeId']);
        if(!$Store){
            return show(config('status.ERROR_STATUS'),'找不到该店铺','找不到该店铺');
        }
        $Ticket = \app\admin\model\Ticket::where(['storeId'=>$param['storeId'],'status'=>5])->select();
        if($Ticket){
            return show(config('status.SUCCESS_STATUS'),'ok',$Ticket);
        }
    }

    public function getStoreDetails(Request $request){
        $param = $request->param();
        if(!$param['storeId']){
            return show(config('status.ERROR_STATUS'),'店铺ID不能为空','店铺ID不能为空');
        }
        $Store = \app\admin\model\Store::get($param['storeId']);
        if($Store){
            $res = Home::getinstoreAndcountFocus($Store->id);
            $Store['countFocus'] = $res['countFocus'];
            $Store['countInStore'] = $res['countInStore'];
            return show(config('status.SUCCESS_STATUS'),'ok',$Store);
        }else{
            return show(config('status.ERROR_STATUS'),'error',[]);
        }
    }

    //店铺是否被关注
    public function getMyFocus(Request $request){
        $param = $request->param();
        if(!$param['storeId']){
            return show(config('status.ERROR_STATUS'),'缺少店铺ID','缺少店铺ID');
        }
        $Userfocus = Userfocus::where(['storeId'=>$param['storeId'],'userId'=>$param['userId']])->find();
        if($Userfocus){
            return show(config('status.SUCCESS_STATUS'),'',1);
        }else{
            return show(config('status.SUCCESS_STATUS'),'',0);
        }
    }

    //根类型获取店铺
    public function getStoreByType(Request $request){
        //经纬度，分类ID
        $param = $request->param();
        $start = $param['start'];
        $length = $param['length'];
        if(!$param['city']){
            return show(config('status.ERROR_STATUS'),'缺少城市信息','缺少城市信息');
        }
        $where = "WHERE status=1 AND city='$param[city]'";
        if($param['typeId']){
            $where .= " AND typeId='$param[typeId]'";
        }

        if(isset($param['lat']) || isset($param['lng'])){
            //有经纬度
            $StoreList = Db::query("SELECT id,imgUrl,name,lat,lng,(round(6371393 * 2 * asin(sqrt(pow(sin(((lat * pi()) / 180 - ({$param['lat']} * pi()) / 180) / 2), 2) + cos(({$param['lat']} * pi()) / 180) * cos((lat * pi()) / 180) * pow(sin(((lng * pi()) / 180 - ({$param['lng']} * pi()) / 180) / 2), 2))))) AS distance FROM `store` {$where} ORDER BY distance ASC  LIMIT {$start},{$length}");
            $count = count(Db::query("SELECT id,imgUrl,name,lat,lng,(round(6371393 * 2 * asin(sqrt(pow(sin(((lat * pi()) / 180 - ({$param['lat']} * pi()) / 180) / 2), 2) + cos(({$param['lat']} * pi()) / 180) * cos((lat * pi()) / 180) * pow(sin(((lng * pi()) / 180 - ({$param['lng']} * pi()) / 180) / 2), 2))))) AS distance FROM `store` {$where}"));
        }else{
            if($param['status'] == 2){
                $order = 'createDate DESC';
            }else{
                $order = 'inStoreCount DESC';
            }
            $StoreList = Db::query("SELECT id,imgUrl,name FROM `store` {$where} ORDER BY {$order} LIMIT {$start},{$length}");
            $count = count(Db::query("SELECT id,imgUrl,name FROM `store` {$where}"));
        }

        if(!empty($StoreList)){
            foreach ($StoreList as &$v){
                $res = Home::getinstoreAndcountFocus($v['id']);
                $v['countInStore'] = $res['countInStore'];
                $v['countFocus'] = $res['countFocus'];
                $Ticket = Home::getTicket($v['id']);
                if($Ticket){
                    $v['Ticket'] = $Ticket['name'];
                    $v['TicketId'] = $Ticket['id'];
                }else{
                    $v['Ticket'] = '';
                }
            }
            return show_page(config('status.SUCCESS_STATUS'),'ok',$count,$StoreList);
        }else{
            return false;
        }


    }

    public function storeSettlements(Request $request){
        $param = $request->param();
        if(empty($param['storeId'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }

        $start = $param['start'];
        $length = $param['length'];


        $Storesettlement = Storesettlement::where('storeId',$param['storeId'])->limit($start,$length)->select();
        $count = Storesettlement::where('storeId',$param['storeId'])->count();
        if($Storesettlement){
            $data['size'] = $count;
            $data['storeSettlements'] = $Storesettlement;
            return show(config('status.SUCCESS_STATUS'),'ok',$data);
        }else{
            return show(2,'暂无记录',null);
        }
    }

    //店铺收入记录
    public function storeTrades(Request $request){
        $param = $request->param();
        $start = $param['start'];
        $length = $param['length'];
        $res = Storecustradedetail::where('storeId',$param['storeId'])->select();
        if($res){
            $summoney = 0;
            foreach ($res as $v){
                $summoney += (int)$v['proceedsMoney'];
            }
        }
        $jilu = Storecustradedetail::where('storeId',$param['storeId'])->order('proceedsTime DESC')->limit($start,$length)->select();
        $count = Storecustradedetail::where('storeId',$param['storeId'])->count();
        if(!empty($jilu)){
            $data['size'] = $count;
            foreach ($jilu as &$v){
                $user = \app\common\model\User::get($v['userId']);
                $v['user'] = $user;
            }
            $data['data'] = $jilu;
            $data['summoney'] = $summoney;
            return show(config('status.SUCCESS_STATUS'),'ok',$data);
        }else{
            return show(2,'暂无记录',null);
        }

    }

    //店铺支出记录
    public function storeTradez(Request $request){
        $param = $request->param();
        $start = $param['start'];
        $length = $param['length'];
        $res = Storetradedetail::where('payStoreId',$param['storeId'])->select();
        if($res){
            $summoney = 0;
            foreach ($res as $v){
                $summoney += (int)$v['payMoney'];
            }
        }
        $jilu = Storetradedetail::where('payStoreId',$param['storeId'])->order('payTime DESC')->limit($start,$length)->select();
        $count = Storetradedetail::where('payStoreId',$param['storeId'])->count();
        if(!empty($jilu)){
            $data['size'] = $count;
            $data['data'] = $jilu;
            $data['summoney'] = $summoney;

            return show(config('status.SUCCESS_STATUS'),'ok',$data);
        }else{
            return show(2,'暂无记录',null);
        }

    }

}